<?php

namespace app\common\business;

use MongoDB\BSON\ObjectId;
use catcher\exceptions\FailedException;
use app\common\model\PatientInfo as PatientModel;

class Patient
{
    /**
     * 获取家庭成员电话（包含本人）
     * @param string $patientId 患者patientId
     * @return array
     */
    public function getFamilyMembersMobile(string $patientId): array
    {
        //联系人节点
        $family = (new PatientModel())->getOneData(["patientId" => $patientId], "id,name,presentTelphone,relationInfo")->toArray();

        if (empty($family['id']))
        {
            throw new FailedException("patientId错误");
        }

        //没有家庭联系人则添加自己为联系人
        if (empty($family["relationInfo"]))
        {
            //判断患者联系方式是否存在
            if (empty($family['presentTelphone'])) {
                return [];
            }

            $sid = new ObjectId();
            $data['relationInfo'][] = [
                'sid'           => (string) $sid,
                'relation'      => 0,
                'name'          => $family['name'],
                'mobile'        => $family['presentTelphone'],
                'inhospitalWay' => 9,
                'default'       => 1
            ];

            $saveRet = (new PatientModel())->saveData($family['id'], $data);
            if ($saveRet)
            {
                $family = (new PatientModel())->getOneData(["patientId" => $patientId], "relationInfo");
            }else{
                throw new FailedException("没有联系人");
            }
        }

        $is_valids = ['1' => '有效', '2' => '无效'];
        $rets = [];
        foreach ($family["relationInfo"] as $key => $val)
        {
            $is_valid = isset($val['is_valid'])&&!empty($val['is_valid'])?$is_valids[$val['is_valid']]:'有效';
            $ret['sid']          = $val['sid'];
            $ret['name']         = $val['name'];
            $ret['mobile']       = $val['mobile'];
            $ret['mobileName']   = $val['mobile']."(".$val['name'].")"."(".$val['relationName'].")"."(".$is_valid.")";
            $ret['relation']     = $val['relation'];
            $ret['relationName'] = $val['relationName'];
            $ret['default']      = $val['default'];
            $rets[] = $ret;
        }
        return  $rets;
    }

    /**
     * 存储患者基本信息
     * @param array $param  参数
     */
    public function filing(array $param)
    {
        $data = [];
        $data['patientId'] = (string)$param['patient_code'];
        $data['name'] = (string)$param['name'];
        $data['presentTelphone'] = (string)$param['mobile'];
        $data['idType'] = "1";
        $data['idno'] = (string)$data['patient_code'];
        $data['liveStatus'] = "1";
        $data['outList'] = null;
        $data['deleted_at'] = 0;
        $id = (new PatientModel())->insertGetId($data);
        return (new PatientModel())->find($id);
    }
}